package com.amit.struts;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCRequestDAO implements RequestDAO {
	
	

	@Override
	public int postRequest(RequestTO rto) {
		
		int RID=0;
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		try
		{
			con=JDBCUtil.getConnection();
			ps=con.prepareStatement("insert into requests values(?,?,?,?,?)");
			RID=getNextRequestID();
			ps.setInt(1, RID);
			ps.setString(2, rto.getEmpId());
			ps.setString(3, rto.getDescription());
			ps.setString(4, rto.getPriority());
			ps.setString(5, rto.getStatus());
			
			int x=ps.executeUpdate();
		}
		
		catch (Exception e) {
		
			e.printStackTrace();
		}
		
		finally
		{
			JDBCUtil.cleanup(con, ps, rs);
		}
		
		return RID;
	}

	private int getNextRequestID() {
		
		int rid=1;
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		try
		{
			con=JDBCUtil.getConnection();
			ps=con.prepareStatement("select max(reqId) from requests");
			rs=ps.executeQuery();
			if(rs.next())
			{
				int x=rs.getInt(1);
				rid=x+1;
			}
		}
		
		catch (Exception e) {
			e.printStackTrace();
		}
		
		finally
		{
			JDBCUtil.cleanup(con, ps, rs);
		}
		return rid;
	}

}
